package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.uu.utils.uuUtils;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.alipay.Result;
import com.hemaapp.yjnh.bean.Address;
import com.hemaapp.yjnh.bean.AlipayTrade;
import com.hemaapp.yjnh.bean.Cart.ChildItem;
import com.hemaapp.yjnh.bean.ClientInfor;
import com.hemaapp.yjnh.bean.CustomBlogDetail;
import com.hemaapp.yjnh.bean.SubOrder;
import com.hemaapp.yjnh.bean.UnionTrade;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.WeixinTrade;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.BaseButtonDialog;
import com.hemaapp.yjnh.view.PayPasswordDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.unionpay.uppay.PayActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 定制类商品购买时确认订单
 *
 * @author GuiyouZhang
 *         Date：2015年10月8日 下午3:31:30
 *         Email:guiyouzhang@163.com
 */
public class CustomizeConfirm2Activity extends BaseActivity implements
        OnClickListener {

    private final static int REQUEST_ADDRESS = 0x01;
    private final static int REQUEST_FRIEND = 0x02;//朋友代付

    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.address_hint_tv)
    TextView addressHintTv;
    @Bind(R.id.recipient_tv)
    TextView recipientTv;
    @Bind(R.id.tel_tv)
    TextView telTv;
    @Bind(R.id.address_tv)
    TextView addressTv;
    @Bind(R.id.layout_address_1)
    LinearLayout layoutAddress1;
    @Bind(R.id.layout_blog_contain)
    LinearLayout layoutBlogContain;
    @Bind(R.id.tv_addition)
    TextView tvAddition;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
    @Bind(R.id.tv_blog_count)
    TextView tvBlogCount;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.tv_coupons_info1)
    TextView tvCouponsInfo1;
    @Bind(R.id.tv_coupons_info2)
    TextView tvCouponsInfo2;
    @Bind(R.id.tv_coupons_info3)
    TextView tvCouponsInfo3;
    @Bind(R.id.ckbx_stamp)
    CheckBox ckbxStamp;
    @Bind(R.id.layout_food_stamp)
    LinearLayout layoutFoodStamp;
    @Bind(R.id.rbtn_friend)
    RadioButton rbtnFriend;
    @Bind(R.id.layout_friend)
    LinearLayout layoutFriend;
    @Bind(R.id.tv_balance)
    TextView tvBalance;
    @Bind(R.id.rbtn_balance)
    RadioButton rbtnBalance;
    @Bind(R.id.pay_balance_lay)
    LinearLayout payBalanceLay;
    @Bind(R.id.rbtn_alipay)
    RadioButton rbtnAlipay;
    @Bind(R.id.laytou_alipay)
    LinearLayout laytouAlipay;
    @Bind(R.id.rbtn_union)
    RadioButton rbtnUnion;
    @Bind(R.id.layout_unipay)
    LinearLayout layoutUnipay;
    @Bind(R.id.rbtn_wechat)
    RadioButton rbtnWechat;
    @Bind(R.id.layout_wechat)
    LinearLayout layoutWechat;
    @Bind(R.id.tv_submit)
    TextView tvSubmit;


    IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);//微信
    private ClientInfor infor;//账户信息 	包含了粮票和账户余额等信息
    private CustomBlogDetail blogDetail;//某个规格的商品信息

    private ArrayList<RadioButton> rbtns = new ArrayList<RadioButton>();// 存储5中支付方式的RadioButton
    private Address address;
    private SubOrder order;//订单信息
    private User user;
    private String friendNum;//代付人
    private String address_id = "0";//收货地址id    从收货地址获取(若为自提，则填0)
    private double freight = 0.0;//运费
    //粮票相关变量
    private double feeAccount = 0.0;//当前账户余额
    private double availCoupons = 0.0;//当前账户可用粮票数
    private double totalFee = 0.0;//总费用,不适用粮票，且包含运费
    private Integer buycount = 0;//总数量
    private double additionFee = 0;
    private double needCashScores = 0.0;//粮票充足情况下和现金一起支付的粮票数量
    private double finalCashScores = 0.0;//最终和现金一起支付的粮票数量
    private double cashFee = 0.0;//最终使用的现金部分
    private String useCouponHint = "";//已用多少张粮票，还需支付多少现金的提示语。在切换是否使用粮票时使用
    private String memo = "无";//订单备注	若无，则固定传"无"
    DecimalFormat df = new DecimalFormat("#0.00");//保留两位小数
    private BaseButtonDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_buy_confirm3);
        ButterKnife.bind(this);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);
        init();
    }

    @Override
    protected void onResume() {
        String weixinpay = XtomSharedPreferencesUtil.get(mContext, "weixinpay");
        if (weixinpay != null && (weixinpay.equals("1"))) {//说明是从微信支付完成后返回
            XtomSharedPreferencesUtil.save(mContext, "weixinpay", "0");
            String status = XtomSharedPreferencesUtil.get(mContext, "status");
            if ("-1".equals(status)) {  //支付失败
                showTextDialog("支付失败!");
            } else if ("-2".equals(status)) { //支付取消
                showTextDialog("您取消了支付!");
            } else {
                showTextDialog("支付成功");
            }
            toNextPage();
        }
        super.onResume();
    }

    private void init() {
        rbtns.add(rbtnAlipay);
        rbtns.add(rbtnUnion);
        rbtns.add(rbtnWechat);
        rbtns.add(rbtnBalance);
        rbtns.add(rbtnFriend);
        setGood();
        tvAddition.setText("¥"+additionFee);
        if (user != null) {//一定要放在最后，因为上面的操作会计算出需要的总费用
            getNetWorker().clientInfor(user.getToken());
        }
    }

    /**
     * 获取所有商品的运费
     *
     * @return
     */
    private void getTotalFreight() {
        if (isNull(address_id)) {
            tvFreight.setText("运费未知，请先手动选择地址");
            return;
        }
        // 交由后台按照运费规则进行计算
        getNetWorker().billExpressGet(user.getToken(), blogDetail.getId(), "", buycount+"",
                address_id);
    }

    /**
     * 设置显示商品信息
     */
    private void setGood() {
        if (layoutBlogContain.getChildCount() != 0) {
            layoutBlogContain.removeAllViews();
        }
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.layout_goods_info2, null);
        ItemViewHolder ivHolder = new ItemViewHolder();
        itemFindView(view, ivHolder);
        ImageUtils.loadSmalImage(mContext, blogDetail.getImgurl(), ivHolder.img);
        ivHolder.name.setText(blogDetail.getName());
        ivHolder.price.setText("¥" + uuUtils.formatAfterDot2(blogDetail.getPrice()));
        ivHolder.amount.setText("x" + buycount);
        ivHolder.tvSpec.setVisibility(View.GONE);
        layoutBlogContain.addView(view);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent itGoods = new Intent(mContext, CustomizeProductionDetailActivity.class);
                itGoods.putExtra("blog_id", blogDetail.getId());
                startActivity(itGoods);
            }
        });
        tvBlogCount.setText("共" + buycount + "件商品");
        getTotalCouponFee();
        tvCouponsInfo1.setText("可使用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo1, R.drawable.food_stamp_grey);
        tvCouponsInfo1.append(df.format(needCashScores)+"粮票");
    }

    /**
     * 未使用粮票，且已经计算出运费
     *
     * @return
     */
    private double getTotalFee() {
        double totalPrice = 0.0;
        totalPrice += buycount * Double.parseDouble(blogDetail.getPrice());
        return Double.parseDouble(uuUtils.formatAfterDot2(totalPrice+freight+additionFee+""));
    }

    /**
     * 获取全部可用粮票的数量
     *
     * @return
     */
    private void getTotalCouponFee() {
        double score = Double.parseDouble(blogDetail.getScore());
        needCashScores = buycount * score;
    }

    private class ItemViewHolder {
        private ImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        private TextView tvSpec;
    }

    /**
     * 一个订单中的多个商品
     *
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.img = (ImageView) view.findViewById(R.id.iv_goods);
        ivHolder.name = (TextView) view.findViewById(R.id.tv_name);
        ivHolder.price = (TextView) view.findViewById(R.id.tv_price);
        ivHolder.amount = (TextView) view.findViewById(R.id.tv_count);
        ivHolder.tvSpec = (TextView) view.findViewById(R.id.tv_spec);
    }

    private void setItem(ChildItem child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText(child.getPrice());
        ivHolder.tvSpec.setText("");
        if (!isNull(child.getBuycount())) {
            int count = Integer.parseInt(child.getBuycount());
            ivHolder.amount.setText("x" + count);
            buycount += count;
        }
        layoutBlogContain.addView(view);
    }

    private void setAddress(Address address) throws Exception {
        if (address != null) {
            addressHintTv.setVisibility(View.GONE);
            layoutAddress1.setVisibility(View.VISIBLE);
            recipientTv.setText("收件人:" + address.getName());
            telTv.setText(address.getTel());
            addressTv.setText(address.getPosition()+address.getAddress());
            address_id = address.getId();
            getTotalFreight();
            return;
        } else {
            XtomToastUtil.showShortToast(mContext, "请先设置收货地址");
            return;
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOG_GET_BY_SPEC:
            case ORDER_ADD:
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
            case ACCOUNT_GET:
            case ORDER_SAVEOPERATE:
            case INVOICE_SAVE:
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
            case ADDRESS_LIST:
            case BILL_EXPRESSFEE_GET:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOG_GET_BY_SPEC:
            case ORDER_ADD:
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
            case ACCOUNT_GET:
            case FEEACCOUNT_REMOVE:
            case ORDER_SAVEOPERATE:
            case SCORE_REMOVE:
            case INVOICE_SAVE:
            case ADDRESS_LIST:
            case BILL_EXPRESSFEE_GET:
                cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ACCOUNT_GET:
                HemaArrayResult<ClientInfor> cResult = (HemaArrayResult<ClientInfor>) baseResult;
                infor = cResult.getObjects().get(0);
                if (!isNull(infor.getFeeaccount())) {
                    feeAccount = Double.parseDouble(uuUtils.formatAfterDot2(infor.getFeeaccount()));
                    tvBalance.setText("（可用¥" + feeAccount + ")");
                }
                if (!isNull(infor.getScore())) {
                    availCoupons = Double.parseDouble(infor.getScore());
                    tvCouponsInfo2.setText("该商品可用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
                    tvCouponsInfo2.append(needCashScores + "粮票 (可用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
                    tvCouponsInfo2.append(uuUtils.formatAfterDot2(infor.getScore())+"粮票)");
                    getNetWorker().addressList(user.getToken());
                } else {
                    XtomToastUtil.showLongToast(mContext, "用户信息异常，请稍后再试");
                }
                break;
            case ORDER_ADD:
                showTextDialog("生成订单成功");
                HemaArrayResult<SubOrder> sResult = (HemaArrayResult<SubOrder>) baseResult;
                //如果是多个商品那么就生成多个订单号
                order = sResult.getObjects().get(0);
                if (rbtnBalance.isChecked() || finalCashScores > 0)
                    showPasDialog();
                else
                    toTrade("");
                break;
            case ALIPAY:
                @SuppressWarnings("unchecked")
                HemaArrayResult<AlipayTrade> aResult = (HemaArrayResult<AlipayTrade>) baseResult;
                AlipayTrade trade = aResult.getObjects().get(0);
                String orderInfo = trade.getAlipaysign();
                new AlipayThread(orderInfo).start();
                break;
            case UNIONPAY:
                HemaArrayResult<UnionTrade> uResult = (HemaArrayResult<UnionTrade>) baseResult;
                UnionTrade uTrade = uResult.getObjects().get(0);
                String uInfo = uTrade.getTn();
                UPPayAssistEx.startPayByJAR(this, PayActivity.class, null, null,
                        uInfo, BaseConfig.UNIONPAY_TESTMODE);
                break;
            case WEIXINPAY:
                @SuppressWarnings("unchecked")
                HemaArrayResult<WeixinTrade> wResult = (HemaArrayResult<WeixinTrade>) baseResult;
                WeixinTrade wTrade = wResult.getObjects().get(0);
                goWeixin(wTrade);
                break;
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
                showTextDialog("支付成功");
                toNextPage();
                break;
            case ORDER_SAVEOPERATE:
                showTextDialog("等待朋友代付");
                toNextPage();
                break;
            case INVOICE_SAVE:
                XtomToastUtil.showShortToast(mContext, "发票保存成功");
                toNextPage();
                break;
            case ADDRESS_LIST:
                HemaPageArrayResult<Address> adResult = (HemaPageArrayResult<Address>) baseResult;
                if (adResult == null || adResult.getObjects() == null || adResult.getObjects().size() == 0) {
                    return;
                }
                address = adResult.getObjects().get(0);
                try {
                    setAddress(address);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case BILL_EXPRESSFEE_GET:
                HemaArrayResult<String> sResult1 = (HemaArrayResult<String>) baseResult;
                String express = sResult1.getObjects().get(0);
                if (!isNull(express)) {
                    freight = Double.parseDouble(express);
                    //计算总费用
                    cashFee = totalFee = getTotalFee();
                    tvTotalFee.setText("¥" + getTotalFee() + "");
                    tvFreight.setText("¥" + freight + "");
                    checkScores();
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(totalFee+""));
                }
                break;
            default:
                break;
        }
    }

    private void goWeixin(WeixinTrade trade) {
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);

        PayReq request = new PayReq();
        request.appId = trade.getAppid();
        request.partnerId = trade.getPartnerid();
        request.prepayId = trade.getPrepayid();
        request.packageValue = trade.getPackageValue();
        request.nonceStr = trade.getNoncestr();
        request.timeStamp = trade.getTimestamp();
        request.sign = trade.getSign();
        msgApi.sendReq(request);
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_ADD:
            case ACCOUNT_GET:
                showTextDialog(baseResult.getMsg());
                break;
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
                showTextDialog("支付失败，\n请到订单列表中查看");
                toNextPage();
                break;
            case ORDER_SAVEOPERATE:
                showTextDialog("申请代付失败，\n请到订单列表中查看");
                toNextPage();
                break;
            case INVOICE_SAVE:
                XtomToastUtil.showShortToast(mContext, "发票保存失败，" + baseResult.getMsg());
                toNextPage();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ACCOUNT_GET:
                showTextDialog("获取账户信息失败");
                break;
            case ORDER_ADD:
                showTextDialog("订单生成失败");
                break;
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
            case ORDER_SAVEOPERATE:
                showTextDialog("支付失败，\n请到订单列表中查看");
                toNextPage();
                break;
            case INVOICE_SAVE:
                XtomToastUtil.showShortToast(mContext, "发票保存失败");
                toNextPage();
                break;
            default:
                break;
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        blogDetail = (CustomBlogDetail) mIntent.getSerializableExtra("blog");
        buycount = mIntent.getIntExtra("buycount", 1);
        additionFee = mIntent.getDoubleExtra("additionFee", 0);
    }

    @Override
    protected void setListener() {
        titleText.setText("确认订单");
        //选择粮票
        ckbxStamp.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (rbtnFriend.isChecked()) {
                        dialog = new BaseButtonDialog(mContext);
                        dialog.setText("代付不能使用粮票\n请选择其它支付方式");
                        dialog.setRightButtonText("确定");
                        dialog.setButtonListener(buttonListener);
                        ckbxStamp.setChecked(false);
                        return;
                    }else {
                        cashFee = totalFee - finalCashScores;
                        tvCouponsInfo3.setText("您已使用");
                        BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                        tvCouponsInfo3.append(useCouponHint);
                    }
                } else {
                    cashFee = totalFee;
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(totalFee+""));
                }
            }
        });
    }

    private void setRbtn(RadioButton rbtn) {
        for (RadioButton rb : rbtns) {
            if (rbtn.equals(rb)) {
//                rb.setChecked(true);
                rb.setChecked(!rb.isChecked());
            } else {
                rb.setChecked(false);
            }
        }
    }

    @OnClick({R.id.title_left_btn, R.id.layout_food_stamp,
            R.id.layout_friend, R.id.pay_balance_lay, R.id.laytou_alipay, R.id.layout_unipay,
            R.id.layout_wechat, R.id.tv_submit, R.id.layout_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_address:
                Intent itAddress = new Intent(mContext, AddressActivity.class);
                itAddress.putExtra("type", 2);
                startActivityForResult(itAddress, REQUEST_ADDRESS);
                break;
            case R.id.layout_food_stamp:
                ckbxStamp.setChecked(!ckbxStamp.isChecked());
                break;
            case R.id.layout_friend:
                String name = "";
                name = blogDetail.getName();
                Intent itFriend = new Intent(mContext, FriendPayActivity.class);
                itFriend.putExtra("name", name);
                itFriend.putExtra("fee", totalFee + "");
                itFriend.putExtra("info", user.getNickname() + "(" + user.getUsername() + ")");
                startActivityForResult(itFriend, REQUEST_FRIEND);
                break;
            case R.id.pay_balance_lay:
                setRbtn(rbtnBalance);
                break;
            case R.id.laytou_alipay:
                setRbtn(rbtnAlipay);
                break;
            case R.id.layout_unipay:
                setRbtn(rbtnUnion);
                break;
            case R.id.layout_wechat:
                setRbtn(rbtnWechat);
                break;
            case R.id.tv_submit:
                if (address == null) {
                    dialog = new BaseButtonDialog(mContext);
                    dialog.setText("请选择收货地址");
                    dialog.setRightButtonText("确定");
                    dialog.setButtonListener(buttonListener);
                    break;
                }
                if (!rbtnAlipay.isChecked() && !rbtnBalance.isChecked()
                        && !rbtnFriend.isChecked() && !rbtnUnion.isChecked() && !rbtnWechat.isChecked()) {
                    if (cashFee > 0 || !ckbxStamp.isChecked()) {//非全粮票购买
                        dialog = new BaseButtonDialog(mContext);
                        dialog.setText("请选择支付方式");
                        dialog.setRightButtonText("确定");
                        dialog.setButtonListener(buttonListener);
                        break;
                    }
                }
                if (rbtnWechat.isChecked() && !msgApi.isWXAppInstalled()) {//如果选择了微信支付，那么先判断是否安装了微信
                    showTextDialog("未检测到您手机的微信");
                    break;
                }
                if (!ckbxStamp.isChecked()) {//如果没有使用粮票，那么全部用现金支付
                    finalCashScores = 0.0;
                }
                String additionIds = mIntent.getStringExtra("addition_ids");
                getNetWorker().orderAdd(user.getToken(), "3", blogDetail.getId(), "无", additionIds, address_id, buycount + "",
                        "无", "无", memo, "无", "无");
                break;
        }
    }
    public void showPasDialog() {
        PayPasswordDialog dialog = new PayPasswordDialog(mContext);
        dialog.setClickListener(new PayPasswordDialog.onPasswordClickListener() {
            @Override
            public void onPasswordConfirm(String password) {
                    toTrade(password);
            }

            @Override
            public void onPasswordCancel() {
                toNextPage();
            }
        });
        dialog.builder().show();
    }

    private void toTrade(String password) {
        if (cashFee == 0) {//如果现金部分为0，那么调用全粮票支付
            scoreRemove(password);
            return;
        }
        if (rbtnAlipay.isChecked()) {
            alipayTrade(password);
        }
        if (rbtnUnion.isChecked()) {
            uppayTrade(password);
        }
        if (rbtnWechat.isChecked()) {
            weixinTrade(password);
        }
        if (rbtnFriend.isChecked()) {
            //朋友代付执行下面的操作
            getNetWorker().orderSaveoperate(user.getToken(),
                    order.getBill_ids() + "," + friendNum, "7", "无", "无", "无", "无");
        }
        if (rbtnBalance.isChecked()) {
            if (cashFee > feeAccount) { // 余额不足
                XtomToastUtil.showShortToast(mContext, "余额不足，请先充值");
                toNextPage();
//                HemaButtonDialog dialog = new HemaButtonDialog(mContext);
//                dialog.setText("抱歉余额不足\n是否去充值？");
//                dialog.setLeftButtonText("取消");
//                dialog.setRightButtonText("充值");
//                dialog.setButtonListener(new OnButtonListener() {
//
//                    @Override
//                    public void onRightButtonClick(HemaButtonDialog dialog) {
//                        dialog.cancel();
//                        Intent it = new Intent(mContext, ChargeMoneyActivity.class);
//                        it.putExtra("type", 1);
//                        mContext.startActivity(it);
//                    }
//
//                    @Override
//                    public void onLeftButtonClick(HemaButtonDialog dialog) {
//                        dialog.cancel();
//                        toNextPage();
//                    }
//                });
//                dialog.show();
            } else {
                feeaccountRemove(password);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ADDRESS:
                try {
                    address = (Address) data.getSerializableExtra("address");
                    setAddress(address);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_FRIEND:
                friendNum = data.getStringExtra("phone");
                setRbtn(rbtnFriend);
                ckbxStamp.setChecked(false);
                break;
            default:
                //银联的支付回调
                if (data == null) {
                    return;
                }
                String msg = "";
            /*
			 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
			 */
                String str = data.getExtras().getString("pay_result");
                if (str.equalsIgnoreCase("success")) {
                    msg = "支付成功！";
                    showTextDialog(msg);
                } else if (str.equalsIgnoreCase("fail")) {
                    msg = "支付失败！";
                    showTextDialog(msg);
                } else if (str.equalsIgnoreCase("cancel")) {
                    msg = "您取消了支付";
                    showTextDialog(msg);
                }
                toNextPage();
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 全粮票购买
     */
    private void scoreRemove(String password) {
        if (user != null) {
            getNetWorker().scoreRemove(user.getToken(), "1", order.getBill_ids(), finalCashScores + "", password);
        }
    }

    //余额购买

    /**
     * 后期设计不需要支付密码，这里的密码可以去掉，也可以随便传一个字符串
     *
     * @param password
     */
    private void feeaccountRemove(String password) {
        getNetWorker().feeaccountRemove(user.getToken(), "1",
                order.getBill_ids(), password, cashFee + "", finalCashScores + "");
    }

    // 支付宝
    private void alipayTrade(String password) {
        getNetWorker().alipay(user.getToken(), "1", "2", order.getBill_ids(), cashFee + "", finalCashScores + "", password);
    }

    // 银联
    private void uppayTrade(String password) {
        getNetWorker().unionpay(user.getToken(), "2", "2", order.getBill_ids(), cashFee + "", finalCashScores + "", password);
    }

    // 微信
    private void weixinTrade(String password) {
        getNetWorker().weixinpay(user.getToken(), "3", "2", order.getBill_ids(), cashFee + "", finalCashScores + "", password);
    }

    private class AlipayThread extends Thread {
        String orderInfo;
        AlipayHandler alipayHandler;

        public AlipayThread(String orderInfo) {
            this.orderInfo = orderInfo;
            alipayHandler = new AlipayHandler(CustomizeConfirm2Activity.this);
        }

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(CustomizeConfirm2Activity.this);
            String result = alipay.pay(orderInfo);

            log_i("result = " + result);
            Message msg = new Message();
            msg.obj = result;
            alipayHandler.sendMessage(msg);
        }
    }

    private class AlipayHandler extends Handler {
        CustomizeConfirm2Activity activity;

        public AlipayHandler(CustomizeConfirm2Activity activity) {
            this.activity = activity;
        }

        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            // activity.showTextDialog(result.getResult());
            int staus = result.getResultStatus();
            switch (staus) {
                case 9000:
                    activity.showTextDialog("支付成功");
                    toNextPage();
                    break;
                default:
                    activity.showTextDialog(result.getResult());
                    toNextPage();
                    break;
            }
        }

        ;
    }

    private BaseButtonDialog.OnButtonListener buttonListener =
            new BaseButtonDialog.OnButtonListener() {

                @Override
                public void onRightButtonClick(BaseButtonDialog dialog) {
                    dialog.cancel();
                }

                @Override
                public void onLeftButtonClick(BaseButtonDialog dialog) {

                }
            };

    /**
     * 当用户选择使用粮票支付时，
     * 判断用户的粮票数量，是否满足要求
     */
    private void checkScores() {
        if (availCoupons >= needCashScores) {
            finalCashScores = needCashScores;
        } else {//如果可用粮票不够支付这两种粮票支付方式
            finalCashScores = availCoupons;//可用粮票部分全部用于支付现金部分的粮票
        }
        String fee = (totalFee - finalCashScores) + "";
        useCouponHint = finalCashScores + "粮票，还需支付¥" + fee;
    }

    /**
     * 跳转到下一个界面
     * 用于支付成功或者失败
     */
    private void toNextPage() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
//                Intent itDtl = new Intent(mContext, BuyerCustomOrderDetailActivity.class);
//                itDtl.putExtra("order_id", order.getBill_ids());
//                startActivity(itDtl);
                finish();
            }
        }, 1000);
    }
}
